/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import model.ArtikelBean;
import model.UserBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DBController.ArtikelDB;

/**
 *
 * @author brlnt
 */
public class ArtikelServlet extends HttpServlet {
    
    protected void halamanArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            List listArtikel = new ArtikelDB().getAllArtikelDiterbitkan();
            request.setAttribute("listArtikel", listArtikel);
            request.setAttribute("title", "Artikel");
            request.getRequestDispatcher("/WEB-INF/view/view_artikel.jsp").forward(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void halamanArtikelBaru(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("title", "Tambah Artikel");
        request.setAttribute("action", "Terbitkan");
        request.setAttribute("alamat", "./tambah_artikel");
        request.getRequestDispatcher("WEB-INF/view/insert_artikel.jsp").forward(request, response);
    }
    
    private void halamanLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/front/login.jsp").forward(request, response);
    }
    
    private void tambahArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        UserBean dataUser = (UserBean) session.getAttribute("sesiUser");
        ArtikelBean dataArtikel = new ArtikelBean();
        
        dataArtikel.setJudul(request.getParameter("judul"));
        dataArtikel.setIsiArtilkel(request.getParameter("isi"));
        dataArtikel.setStatus(1);
        dataArtikel.setUser(dataUser);
        
        ArtikelDB artikel = new ArtikelDB();
        artikel.insertArtikel(dataArtikel);
        //doGet
        response.sendRedirect("artikel");
    }
    
    private void halamanKelolaArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            HttpSession session = request.getSession();
            UserBean dataUser = (UserBean) session.getAttribute("sesiUser");
            int id = dataUser.getIdUser();
            List listArtikel = new ArtikelDB().getArtikelByUser(id);
            request.setAttribute("listArtikel", listArtikel);
            request.setAttribute("title", "Kelola Artikel");
            request.getRequestDispatcher("/WEB-INF/view/kelola_artikel.jsp").forward(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void halamanEditArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            int id = Integer.valueOf(request.getParameter("id"));
            List list = (List) new ArtikelDB().getArtikelByID(id);
            ArtikelBean dataArtikel = (ArtikelBean) list.get(0);
            request.setAttribute("dataArtikel", dataArtikel);
            request.setAttribute("action", "Perbarui");
            request.setAttribute("title", "Edit Artikel");
            request.setAttribute("alamat", "./update_artikel");
            request.getRequestDispatcher("WEB-INF/view/insert_artikel.jsp").forward(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void viewSingleArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            int id = Integer.valueOf(request.getParameter("id"));
            List list = new ArtikelDB().getArtikelByID(id);
            ArtikelBean dataArtikel = (ArtikelBean) list.get(0);
            request.setAttribute("dataArtikel", dataArtikel);
            request.setAttribute("title", dataArtikel.getJudul());
            request.getRequestDispatcher("/WEB-INF/view/view_single_artikel.jsp").forward(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ArtikelServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        UserBean ubean = (UserBean) session.getAttribute("sesiUser");
        ArtikelDB artikeldb = new ArtikelDB();
        String path = request.getServletPath();
        // tidak perlu login
        if (path.equals("/artikel")) {
            String id = request.getParameter("id");
            if (id == null) {
                halamanArtikel(request, response);
            } else {
                viewSingleArtikel(request, response);
            }
        }
        // validasi login
        if (ubean != null) {
            int uid = ubean.getIdUser();
            
            if (ubean.getRole() == 2) {
                // kalau validator
                String id = request.getParameter("id");
                if (path.equals("/kelola_artikel")) {
                    halamanKelolaArtikel(request, response);
                } else if (path.equals("/artikel_baru")) {
                    halamanArtikelBaru(request, response);
                } else if (path.equals("/edit_artikel")) {
                    if (id != null) {
                        int idart = Integer.valueOf(id);
                        if (artikeldb.hakEdit(idart, uid)) {
                            halamanEditArtikel(request, response);
                        } else {
                            response.sendError(401);
                        }
                    } else {
                        halamanKelolaArtikel(request, response);
                    }
                }
            } else {
                response.sendError(401);
            }
        } else {
            halamanLogin(request, response);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        HttpSession session = request.getSession();
        UserBean ubean = (UserBean) session.getAttribute("sesiUser");
        
        String path = request.getServletPath();
        
        if (ubean != null) {
            if (ubean.getRole() == 2) {
                if (path.equals("/tambah_artikel")) {
                    tambahArtikel(request, response);
                } else if (path.equals("/simpan_artikel")) {
                    simpanArtikel(request, response);
                } else if (path.equals("/update_artikel")) {
                    editArtikel(request, response);
                } else if (path.equals("/hapus_artikel")) {
                    hapusArtikel(request, response);
                }
            }
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void editArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ArtikelBean dataArtikel = new ArtikelBean();
        dataArtikel.setJudul(request.getParameter("judul"));
        dataArtikel.setIsiArtilkel(request.getParameter("isi"));
        dataArtikel.setIdArtikel(Integer.valueOf(request.getParameter("id")));
        dataArtikel.setStatus(1);
        new ArtikelDB().editArtikel(dataArtikel);
        response.sendRedirect("./artikel");
    }
    
    private void hapusArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.valueOf(request.getParameter("id"));
        new ArtikelDB().deleteArtikel(id);
        response.sendRedirect("./kelola_artikel");
    }
    
    private void simpanArtikel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        UserBean dataUser = (UserBean) session.getAttribute("sesiUser");
        
        ArtikelBean dataArtikel = new ArtikelBean();
        ArtikelDB artikeldb = new ArtikelDB();
        
        dataArtikel.setUser(dataUser);
        dataArtikel.setJudul(request.getParameter("judul"));
        dataArtikel.setIsiArtilkel(request.getParameter("isi"));
        if (request.getParameter("id") == null) {
            dataArtikel.setStatus(2);
            artikeldb.insertArtikel(dataArtikel);
        } else {
            dataArtikel.setIdArtikel(Integer.valueOf(request.getParameter("id")));
            dataArtikel.setStatus(2);
            artikeldb.editArtikel(dataArtikel);
        }
        response.sendRedirect("./kelola_artikel");
    }
}
